package com.app.business.service;

import com.app.business.model.Contract;
import com.app.business.model.OverAreaPrice;
import com.app.system.jpa.JpaBaseDao;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 超出房源面积单价配置
 * Created by ZYK on 2019/2/25.
 */
@SuppressWarnings(value = "ALL")
@Service
@Transactional
public class OverAreaPriceService extends JpaBaseDao<OverAreaPrice,Integer> {

    @Autowired
    private ContractService contractService;

    /**
     * 删除某一征收项目下所有的面积区间配置数据
     * @param zsProjectId
     */
    public synchronized void deleteOverAreaPriceByZsProjectId(Integer zsProjectId){
        String sql = "delete from over_area_price where zs_project_id = :zsProjectId";
        this.entityManager.createNativeQuery(sql).setParameter("zsProjectId",zsProjectId).executeUpdate();
    }

    /**
     * 通过征收项目得到下面所有的面积区间分配
     *
     * @return
     */
    public List<OverAreaPrice> getOverAreaPriceListByZsProjectId(Integer zsProjectId) {
        //查询语句
        StringBuffer hql = new StringBuffer("from OverAreaPrice oap where oap.zsProject.id =:zsProjectId order by oap.sortNum,oap.id");
        Map<String,Object> map = new HashMap<>();
        map.put("zsProjectId",zsProjectId);
        return this.findHql(hql.toString(),map);
    }

    /**
     * 获取某个协议下扩购面积各区间扩购面积及购房款
     * @param contractId
     * @return
     */
    public Map<String,Map> getOverHouseMoneyMap(Contract contract){
        Map<String,Map> resultMap = Maps.newLinkedHashMap();
        if (contract == null || contract.getZsProject() == null){
            return resultMap;
        }
        List<OverAreaPrice> overAreaPriceList = this.getOverAreaPriceListByZsProjectId(contract.getZsProject().getId());
        if (CollectionUtils.isNotEmpty(overAreaPriceList)){
            //选房超出面积，先取出选房超出的面积
            BigDecimal zzResultArea = BigDecimalUtils.getNotNull(contract.getZzResultArea());
            //定义每一个面积段的最小、最大、差值（最大-最小）
            BigDecimal minArea = BigDecimal.ZERO, maxArea = BigDecimal.ZERO,itemSubArea = BigDecimal.ZERO;
            //定义面积段的长度
            int overAreaPriceListLength = overAreaPriceList.size();
            //循环每一个面积段
            for (int i = 0; i < overAreaPriceListLength; i++){
                //取出面积段bean
                OverAreaPrice overAreaPrice = overAreaPriceList.get(i);
                //最小面积
                minArea = BigDecimalUtils.getNotNull(overAreaPrice.getMinArea());
                //最大面积
                maxArea = BigDecimalUtils.getNotNull(overAreaPrice.getMaxArea());
                //区间面积的差值
                itemSubArea = BigDecimalUtils.getBigAndBigSub(maxArea,minArea);
                //定义面积段的key值：（在财务表中也会显示）
                String areaKey = overAreaPrice.getMinArea()+"-"+overAreaPrice.getMaxArea()+"(含)";
                //如果是最后一个面积段，key值为:  面积（以上）
                if (i == overAreaPriceListLength - 1){
                    areaKey = overAreaPrice.getMinArea()+"以上";
                }
                //定义本次面积段超出的面积以及需要花费的购房款
                BigDecimal itemAreaValue = BigDecimal.ZERO, itemMoneyValue = BigDecimal.ZERO;
                Map itemMap = Maps.newLinkedHashMap();

                //选房面积超出限量面积才去进行计算，没超出的话，全是""（后来添加，用来处理财务结算表显示问题）
                if (BigDecimalUtils.getBigAndBigSub(contract.getChooseHouseAreaTotal(),contract.getLimitHouseAreaTotal()).compareTo(BigDecimal.ZERO) > 0){
                    if (zzResultArea.compareTo(itemSubArea) <= 0){
                        //如果当前选房超出面积 <= 该区间面积的差值，直接将当前超出的面积赋给本区间的面积即可
                        itemAreaValue = zzResultArea;
                        //计算需要花费的购房款（为负数：被征收人应缴纳金额）
                        itemMoneyValue =  BigDecimalUtils.getBigAndBigMul(itemAreaValue,overAreaPrice.getPrice()).setScale(0,BigDecimal.ROUND_HALF_UP).negate();
                        zzResultArea = BigDecimal.ZERO;   //该循环后，超出面积为0了
                    }else {
                        //否则，本段超出面积为：最大面积 - 最小面积
                        itemAreaValue = BigDecimalUtils.getBigAndBigSub(maxArea,minArea);
                        //计算需要花费的购房款（为负数：被征收人应缴纳金额）
                        itemMoneyValue = BigDecimalUtils.getBigAndBigMul(itemAreaValue,overAreaPrice.getPrice()).setScale(0,BigDecimal.ROUND_HALF_UP).negate();
                        zzResultArea = BigDecimalUtils.getBigAndBigSub(zzResultArea,itemSubArea);   //该循环后超出面积应把此区间内的面积差减去，为当前还剩余超出的面积
                    }
                }

                itemMap.put("area",BigDecimalUtils.getNotNullStr(itemAreaValue));
                itemMap.put("price",BigDecimalUtils.getNotNullStr(overAreaPrice.getPrice()));
                itemMap.put("money",BigDecimalUtils.getNotNullStr(itemMoneyValue));
                resultMap.put(areaKey,itemMap);
            }
        }
        return resultMap;
    }
}
